package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.common.constants.ScheduleConstants;
import com.zhentao.common.redis.CacheService;
import com.zhentao.mapper.TaskinfoLogsMapper;
import com.zhentao.mapper.TaskinfoMapper;
import com.zhentao.model.schedule.dto.Task;
import com.zhentao.model.schedule.pojo.Taskinfo;
import com.zhentao.model.schedule.pojo.TaskinfoLogs;
import com.zhentao.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Slf4j
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加延时任务
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {

        Boolean flag = false;
        try {
            //添加任务到数据库中
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        //添加任务到Redis中
        if(flag){
            //添加任务 到Redis
            //  任务执行时间小于当前时间      currentTimeMillis  当前毫秒值  存入List
            //                 任务执行类型           当前优先级
            String key = task.getTaskType()+"_"+task.getPriority();

            //获取5分钟之后的时间
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, 5);
            long nextScheduleTime = calendar.getTimeInMillis();

            if(task.getExecuteTime() <= System.currentTimeMillis()){
                //如果任务执行时间小于当前时间 存入List
                cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
            }else if (task.getExecuteTime() <= nextScheduleTime){
                //如果任务执行时间大于当前时间 小于等于预设时间（未来5分钟） 存入zset
                cacheService.zAdd(ScheduleConstants.FUTURE+key, JSON.toJSONString(task), task.getExecuteTime());

            }
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     * @param taskId
     * @return
     */
    @Override
    public Boolean cancelTask(Long taskId) {
        boolean flag = false;

        Task task = updateBb(taskId,ScheduleConstants.CANCELLED);
        //删除Redis中的数据
        if(task != null){
            removeTaskFromCache(task);
            flag = true;
        }

        return false;
    }

    /**
     * 按照类型和优先级 拉取任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(Integer type, Integer priority) {
        Task task = null;
        try {
            String key = type+"_"+priority;
            //从Redis中拉取数据
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if(StringUtils.isNotBlank(task_json)){
                //转换成task对象
                task = JSON.parseObject(task_json, Task.class);
                //修改数据库的信息
                updateBb(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return task;
    }

    //删除任务  更新日志
    private Task updateBb(Long taskId, int status) {
        Task task = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);
            //更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            //从日志中获取 task
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return task;
    }
    //删除Redis中的数据
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        if(task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key, 0, JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key, JSON.toJSONString(task));
        }
    }

    /**
     * 未来数据定时刷新  每分钟刷新一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){
        //分布式锁
        String token = cacheService.tryLock("FUTRUE_TASK_SYNC", 1000 * 30);
        if(StringUtils.isNotBlank(token)){
            log.info("未来数据定时刷新---定时任务");

            //获取所有未来数据的集合
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");// future_*
            for (String futureKey : futureKeys) {// future_100_50
                System.err.println("定时任务:"+new Date()+futureKey);

                //获取当前数据的key  topic
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //按照key 和分值查询符合条件的数据
                //这里拿到 一个一个的任务
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                //同步数据  Redis 管道技术
                if(!tasks.isEmpty()){
                    cacheService.refreshWithPipeline(futureKey, topicKey,tasks);
                    log.info("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                }
            }
        }
    }


    /**
     * 数据库任务 定时同步到Redis中
     */
    @PostConstruct//初始化 一旦微服务启动 都会做一个同步操作
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        //清理缓存中的数据
        //List中的   zset 中的
        clearCache();
        //查询符合条件的任务  小于未来五分钟的数据
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        //将任务添加到Redis
        if(taskinfoList != null && taskinfoList.size() > 0){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTask(task);
            }
        }
        log.info("数据库的任务同步到了redis");
    }


    /**
     * 清理缓存中的数据
     */
    public void clearCache(){
        Set<String> TOPICKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");//TOPIC
        Set<String> FUTUREKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");//FUTURE

        cacheService.delete(TOPICKeys);
        cacheService.delete(FUTUREKeys);
    }



}
